package com.vanguard.utils;

import com.vanguard.file.BufferedRandomAccessFile;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: 文件操作工具类
 * @Description:
 * @Author: vanguard
 * @Version: 1.0
 * @Date: 2018/11/29
 */
public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 通过BufferedRandomAccessFile读取文件,推荐
     *
     * @param file     源文件
     * @param encoding 文件编码
     * @param pos      偏移量
     * @param num      读取量
     * @return pins文件内容，pos当前偏移量
     */
    public static Map<String, Object> bufferedRandomAccessFileReadLine(File file, String encoding, long pos, int num) {
        Map<String, Object> res = new HashMap<>();
        List<String> pins = new ArrayList();
        res.put("pins", pins);
        BufferedRandomAccessFile reader = null;
        try {
            reader = new BufferedRandomAccessFile(file, "r");
            reader.seek(pos);
            for (int i = 0; i < num; i++) {
                String pin = reader.readLine();
                if (StringUtils.isBlank(pin)) {
                    break;
                }
                pins.add(new String(pin.getBytes("8859_1"), encoding));
            }
            res.put("pos", reader.getFilePointer());
        } catch (Exception e) {
            return null;
        } finally {
            IOUtils.closeQuietly(reader);
        }
        return res;
    }

    /**
     * 从文件开始位置写入数据
     * @param file
     * @param encoding
     * @param buffer
     */
    public static void writeStart(File file, String encoding, StringBuffer buffer) {
        BufferedRandomAccessFile writer = null;
        try {
            writer = new BufferedRandomAccessFile(file, "rw");
            String data = new String(buffer.toString().getBytes("8859_1"), encoding);
            writer.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    /**
     * 向文件尾部写入数据
     * @param file
     * @param encoding
     * @param line
     */
    public static void append(File file, String encoding, String line) {
        BufferedRandomAccessFile writer = null;
        try {
            writer = new BufferedRandomAccessFile(file, "rw");
            long pos = writer.length();
            writer.seek(pos);
            String data = new String(line.getBytes("8859_1"), encoding);
            writer.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    /**
     * 向文件尾部写入数据list集合
     * @param file
     * @param encoding
     * @param lines
     */
    public static void append(File file, String encoding, List<String> lines) {
        for(String line : lines) {
            append(file, encoding, line);
        }
    }

    /**
     * 通过RandomAccessFile读取文件，能出来大数据文件，效率低
     *
     * @param file     源文件
     * @param encoding 文件编码
     * @param pos      偏移量
     * @param num      读取量
     * @return pins文件内容，pos当前偏移量
     */
    public static Map<String, Object> readLine(File file, String encoding, long pos, int num) {
        Map<String, Object> res = new HashMap<>();
        List<String> pins = new ArrayList();
        res.put("pins", pins);
        RandomAccessFile reader = null;
        try {
            reader = new RandomAccessFile(file, "r");
            reader.seek(pos);
            for (int i = 0; i < num; i++) {
                String pin = reader.readLine();
                if (StringUtils.isBlank(pin)) {
                    break;
                }
                pins.add(new String(pin.getBytes("8859_1"), encoding));
            }
            res.put("pos", reader.getFilePointer());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(reader);
        }
        return res;
    }

    /**
     * 使用LineNumberReader读取文件，1000w行比RandomAccessFile效率高，无法处理1亿条数据
     *
     * @param file     源文件
     * @param encoding 文件编码
     * @param index    开始位置
     * @param num      读取量
     * @return pins文件内容
     */
    public static List<String> readLine(File file, String encoding, int index, int num) {
        List<String> pins = new ArrayList<>();
        LineNumberReader reader = null;
        try {
            reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), encoding));
            int lines = 0;
            while (true) {
                String pin = reader.readLine();
                if (StringUtils.isBlank(pin)) {
                    break;
                }
                if (lines >= index) {
                    if (StringUtils.isNotBlank(pin)) {
                        pins.add(pin);
                    }
                }
                if (num == pins.size()) {
                    break;
                }
                lines++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(reader);
        }
        return pins;
    }

    /**
     * 创建文件夹 add by ljyan 20111020
     * @param path
     * @return boolean
     */
    public static boolean createDir(String path) {
        boolean createOk = true;
        File dirFile = new File(path);
        if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
            createOk = dirFile.mkdirs();
            if (!createOk) {
                if (logger.isInfoEnabled()) {
                    logger.info("dir create failure!");
                }
            } else {
                createOk = true;
            }
        }
        return createOk;
    }

}
